package com.tompai.ftpan.web.config;

import javax.servlet.MultipartConfigElement;
import javax.sql.DataSource;

import org.apache.ibatis.type.TypeAliasRegistry;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import com.tompai.ftpan.web.entity.File;
import com.tompai.ftpan.web.entity.Resource;
import com.tompai.ftpan.web.entity.ResourceChunk;
import com.zaxxer.hikari.HikariDataSource;

/**
 * @author tompai
 * @date 2020-01-08
 */
@Configuration
public class Config {

	private final FeitianProperties feitianProperties;

	@Autowired
	public Config(FeitianProperties feitianProperties) {
		this.feitianProperties = feitianProperties;
	}

	@Bean
	public MultipartConfigElement multipartConfigElement() {
		MultipartConfigFactory factory = new MultipartConfigFactory();
		factory.setMaxFileSize(DataSize.parse(feitianProperties.getMaxFileUploadSize()));
		factory.setMaxRequestSize(DataSize.parse(feitianProperties.getMaxRequestSize()));
		return factory.createMultipartConfig();
	}

	/**
	 * 自定义mybatis配置
	 * @return ConfigurationCustomizer
	 */
	@Bean
	public ConfigurationCustomizer configurationCustomizer() {
		return configuration -> {
			configuration.setMapUnderscoreToCamelCase(true);

			// 注册别名，用于生产环境识别类别名
			TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();
			typeAliasRegistry.registerAlias(File.ALIAS, File.class);
			typeAliasRegistry.registerAlias(Resource.ALIAS, Resource.class);
			typeAliasRegistry.registerAlias(ResourceChunk.ALIAS, ResourceChunk.class);
		};
	}

	@Bean
	public DataSource buildDataSource() {
		if (feitianProperties.isUseMysql()) {
			return buildMysqlDatasource();
		} else {
			return buildEmbedDbDatasource();
		}
	}

	private DataSource buildMysqlDatasource() {
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setDriverClassName(feitianProperties.getMysqlDriver());
		dataSource.setJdbcUrl(feitianProperties.getMysqlUrl());
		dataSource.setUsername(feitianProperties.getMysqlUsername());
		dataSource.setPassword(feitianProperties.getMysqlPassword());
		return dataSource;
	}

	private DataSource buildEmbedDbDatasource() {
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setDriverClassName(feitianProperties.getEmbedDbDriver());
		dataSource.setJdbcUrl(feitianProperties.getEmbedDbUrl());
		dataSource.setUsername(feitianProperties.getEmbedDbUsername());
		dataSource.setPassword(feitianProperties.getEmbedDbPassword());
		return dataSource;
	}
}
